package com.hq.sys.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.hq.sys.constat.SysConstant;
import com.hq.sys.eneity.User;
import com.hq.sys.eneity.UserVo;
import com.hq.sys.service.UserService;
import com.hq.sys.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * ⽤户登录控制器
 */
@Controller
@RequestMapping("login")
public class LoginController {
    @Autowired
    private UserService userService;

    /**
     * @return 跳转到登录⻚⾯的⽅法
     */
    @RequestMapping("toLogin")
    public String toLogin() {
        return "system/main/login";
    }

    /**
     * .登陆⽅法
     *
     * @param userVo
     * @param model
     * @return
     */
    @RequestMapping("login")
    public String login(UserVo userVo, Model model) {
        String code = WebUtils.getHttpSession().getAttribute("code").toString();
        if (userVo.getCode().equals(code)) {
            User user = this.userService.login(userVo);
            System.out.println("user = " + user);
            if (null != user) {
//放⼊到session
                WebUtils.getHttpSession().setAttribute("user", user);
                return "system/main/index";
            } else {
                model.addAttribute("error",
                        SysConstant.USER_LOGIN_ERROR_MSG);
                return "system/main/login";
            }
        } else {
            model.addAttribute("error",
                    SysConstant.USER_LOGIN_CODE_ERROR_MSG);
            return "system/main/login";
        }
    }

    //获取验证码
    @RequestMapping("getCode")
    public void getCode(HttpServletResponse response, HttpSession
            session) throws IOException {
//定义图形验证码的⻓和宽
        LineCaptcha lineCaptcha =
                CaptchaUtil.createLineCaptcha(116, 36, 4, 5);
        session.setAttribute("code", lineCaptcha.getCode());
        ServletOutputStream outputStream =
                response.getOutputStream();
        ImageIO.write(lineCaptcha.getImage(), "JPEG", outputStream);
    }
}